package com.qd.p2p.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.adapted.AdaptedRechargeService;
import com.qdlc.p2p.biz.adapted.AdaptedServiceFactory;
import com.qdlc.p2p.biz.service.AccountBankService;
import com.qdlc.p2p.biz.service.AccountRechargeService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.PayOnlinebankService;
import com.qdlc.p2p.biz.util.NotifyRequestUrl;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.BindingBankStatus;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.exception.AccountException;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.PayOnlinebank;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.AccountRechargeModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 充值
 * @author linya 2016-04-13
 */
@SuppressWarnings("rawtypes")
public class RechargeAction extends BaseAction implements ModelDriven<AccountRechargeModel> {

	private AccountRechargeModel model = new AccountRechargeModel();

	@Resource
	private AccountService accountService;
	
	@Resource
	private AccountRechargeService accountRechargeService;
	
	@Resource
	private AccountBankService accountBankService;
	
	@Resource
	private PayOnlinebankService payOnlinebankService;
	
	//充值适配服务接口
	private AdaptedRechargeService adaptedRechargeService = AdaptedServiceFactory.getService(AdaptedRechargeService.class);
	
	/**
	 * 校验是否可充值
	 * @return
	 * @throws Exception
	 */
	@Action(value="/member/recharge/checkNewRecharge")
	public void checkNewRecharge() throws Exception {
		User user = getSessionUser();
		UserIdentify userIdentify = UserUtils.getUserIdentify(user);
		try {
			model.validIdentifyForRecharge(userIdentify);
		} catch (AccountException e) {
			throw new AccountException(e.getMessage(), BusinessException.TYPE_JSON);
		}
	}
	
	/**
	 * 前往充值页面
	 * @return String
	 * @throws Exception if has error
	 */
	@Action(value="/member/recharge/newRecharge",results = { @Result(name = "newRecharge", type = "ftl", location = "/member/recharge/newRecharge.html"),
			@Result(name = "newRecharge_firm", type = "ftl", location = "/member_borrow/recharge/newRecharge.html")})
	public String newRecharge() throws Exception {
		saveToken("newRecharge");
		User user = getSessionUser();
		Account account = accountService.findAccountByUserId(user.getUserId());
		List<PayOnlinebank> payOnlinebankList = payOnlinebankService.findList();
		request.setAttribute("account", account);
		request.setAttribute("payOnlinebankList", payOnlinebankList);
		//获取用户绑定银行卡状态
		BindingBankStatus bankStatus = accountBankService.bindingBankStatus(user.getUserId());
		request.setAttribute("binding_bank_status", bankStatus.getStatus());
		request.setAttribute("binding_bank_message", bankStatus.getMessage());
		//判断是否是企业账户
		if(UserTypeUtils.isInvestmentBorrow(user.getUserId())){
			return "newRecharge_firm";
		}
		return "newRecharge";
	}

	/**
	 * 进行网银充值
	 * @return String
	 * @throws Exception if has error
	 */
	@Action(value="/member/recharge/doRecharge",results={@Result(name = "result", type = "ftl", location = "/member/tpp/" + Constant.TPP_PACKAGE + "/recharge.html")})
	public void doRecharge() throws Exception {
        
		User user = getSessionUser();
		
		//检测充值前置条件
		ReturnResult result = adaptedRechargeService.rechargePreCondition(user, model.getMoney());
		if(result.isError()){
			throw new AccountException(result.getErrorInfo());
		}
		
		//检测Token
        try {
			checkToken("newRecharge");
		} catch (AccountException e) {
			throw new AccountException(e.getMessage());
		}

        //充值处理，成功则跳转到网银页面
		result = adaptedRechargeService.doRecharge(user, model.getMoney(), request);
		if(result.isSuccess()){
            String html = String.valueOf(result.getExtra("html"));
		    this.printHtml(html);
		}else{
			throw new AccountException(result.getErrorInfo());
		}
		
	}
	
	/**
	 * [网银充值]充值回调（宝付）
	 */
	@Action(value=NotifyRequestUrl.RECHARGE_RETURN_NOTIFY_ACTION)
	public void notifyRecharge(){
        adaptedRechargeService.notifying(request, response);
	}
	

	/**
	 * 充值记录列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value="/member/recharge/log",results = { @Result(name = "log", type = "ftl", location = "/member/recharge/log.html"),
			@Result(name = "log_firm", type = "ftl", location = "/member_borrow/recharge/log.html")})
	public String log() throws Exception {
		User user = getSessionUser();
		AccountRechargeModel recharge = accountRechargeService.getRechargeSummary(getSessionUser().getUserId());
		Account account = accountService.findAccountByUserId(user.getUserId());
		request.setAttribute("recharge", recharge);
		request.setAttribute("useMoney", account.getUseMoney());
		request.setAttribute("total", account.getUseMoney() + account.getNoUseMoney()+account.getCollection());
		if (UserTypeUtils.isBorrowOrInverstment(user.getUserId())) {
			return "log_firm";
		} 
		return "log";
	}

	/**
	 * 充值记录 ajax数据接口
	 * 
	 * @return
	 */
	@Action("/member/recharge/logList")
	public void logList() throws Exception {
        User user = getSessionUser();
        long userId = user.getUserId();
        String status = paramString("status");
        if (StringUtil.isBlank(status)) {
            model.setStatus(99);
        }
        PageDataList<AccountRechargeModel> pageDataList = accountRechargeService.list(userId, model);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("data", pageDataList);
        printWebJson(getStringOfJpaObj(data));
    }

	@Override
	public AccountRechargeModel getModel() {
		return model;
	}
	
}
